/**
 * router/index.ts
 *
 * Automatic routes for `./src/pages/*.vue`
 */

// import { setupLayouts } from 'virtual:generated-layouts'
// Composables
import { createRouter, createWebHistory } from 'vue-router'
// export { routes as autoRoutes } from 'vue-router/auto-routes'
import { routes } from './routes'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: (routes),
})

// 预加载即将进入的懒加载组件，避免首次进入时的加载停顿
function preloadRouteComponents(to: any) {
  return Promise.all(
    to.matched.map((r: any) => {
      // 兼容默认视图与命名视图两种写法
      const comps = r.components ?? (r.component ? { default: r.component } : {})
      return Promise.all(
        Object.values(comps).map((c: any) => {
          if (typeof c === 'function') return c() // 触发 import() 预拉取
        })
      )
    })
  )
}

router.beforeEach(async (to, from, next) => {
  try {
    await preloadRouteComponents(to)
  } catch (e) {
    console.error('Prefetch route components failed:', e)
  }
  next()
})

// 修改：不再强制整页刷新，保持 SPA 导航
router.onError((err, to) => {
  if (err?.message?.includes?.('Failed to fetch dynamically imported module')) {
    console.error('Dynamic import error (no full reload applied):', err)
  } else {
    console.error(err)
  }
})

router.isReady().then(() => {
  localStorage.removeItem('vuetify:dynamic-reload')
})

export default router
